import json

from django.contrib import messages
from django.contrib.auth import get_user_model
from django.contrib.auth.decorators import login_required, permission_required
from django.contrib.auth.mixins import LoginRequiredMixin, PermissionRequiredMixin
from django.contrib.auth.models import Group
from django.core import serializers
from django.db.models import Q
from django.http import HttpResponse, JsonResponse
from django.shortcuts import render
from django.urls import reverse, reverse_lazy
from django.views.decorators.http import require_POST, require_GET
from django.views.generic import ListView, CreateView, TemplateView, UpdateView, DeleteView
from django.views.generic.base import View
from pure_pagination import PaginationMixin
# Create your views here.
from cmdb.models import Host,DataBase, Tag, Type

from .tasks import update_hosts_from_cloud, update_rds_from_cloud
from .summary import assets_overview

User = get_user_model()


class AssetsOverView(View):
    """
    资产大盘
    """
    def get(self, request):
        overview = assets_overview()
        print(overview)
        context = {
            'overview': overview,
        }
        return render(request, 'cmdb/assets_overview.html', context=context)


class HostListView(LoginRequiredMixin,PermissionRequiredMixin,PaginationMixin,ListView):
    """
    资产管理
    """
    model = Host
    paginate_by = 10
    permission_required = 'cmdb.view_host'
    keyword = None
    slug = None

    def get_keyword(self):
        self.keyword = self.request.GET.get('keyword')
        return self.keyword

    def get_slug(self):
        self.slug = self.request.GET.get('tag')
        return self.slug

    def get_queryset(self):
        queryset = super().get_queryset()
        slug = self.get_slug()
        if slug:
            queryset = queryset.filter(tags__name=slug)
        keyword = self.get_keyword()
        if keyword:
            queryset = queryset.filter(Q(instance_id__icontains=keyword) | Q(instance_name__icontains=keyword) |
                                       Q(description__icontains=keyword) | Q(hostname__icontains=keyword) |
                                       Q(public_ip__icontains=keyword) | Q(private_ip__icontains=keyword))
        return queryset

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['keyword'] = self.keyword
        context['slug'] = self.slug
        context['types'] = Type.objects.all()
        context['tags'] = Tag.objects.all()
        context['hosts_count'] = Host.objects.count()
        return context

class HostTagAddView(LoginRequiredMixin,UpdateView):
    """
        给主机添加标签
        """
    template_name = 'cmdb/host_tags.html'
    model = Host
    fields = ('tags',)

    def get_success_url(self):
        if '_addanother' in self.request.POST:
            return reverse('cmdb:host-tags-add', kwargs={'pk': self.object.pk})
        return reverse('cmdb:hosts')

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['tags'] = Tag.objects.all()
        context['hosts_tags'] = self.object.tags.all()
        return context

class DBListView(LoginRequiredMixin, PermissionRequiredMixin, PaginationMixin, ListView):
    """
    数据库列表
    """
    model = DataBase
    paginate_by = 10
    permission_required = 'cmdb.view_database'
    keyword = None

    def get_keyword(self):
        self.keyword = self.request.GET.get('keyword')
        return self.keyword

    def get_queryset(self):
        queryset = super().get_queryset()
        keyword = self.get_keyword()
        if keyword:
            queryset = queryset.filter(Q(public_cloud__icontains=keyword) | Q(account_name__icontains=keyword) |
                                       Q(region_id__icontains=keyword) | Q(zone_id__icontains=keyword) |
                                       Q(instance_id__icontains=keyword) | Q(description__icontains=keyword) |
                                       Q(connection_address__icontains=keyword))
        return queryset

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['keyword'] = self.keyword
        return context



@require_GET
@login_required
@permission_required(perm='cmdb.view_host')
def get_host_list(request):
    """
    获取主机列表接口，返回json
    :return:
    """
    hosts = Host.objects.all()
    tag = request.GET.get('tag',"")
    if tag:
        hosts = Host.objects.filter(tags__name=tag)
    host_list = []
    for host in hosts:
        host_list.append({'id': str(host.id), 'instance_name': host.instance_name, 'ip':host.private_ip})
    return JsonResponse({'code': 0, 'msg': '主机获取成功！', 'data': host_list})


@require_GET
@login_required
def update_host_info(request):
    """
    更新资产信息信息
    :param request:
    :return:
    """
    update_hosts_from_cloud.delay()
    # update_rds_from_cloud.delay()
    return HttpResponse('任务已提交到后台，请稍等片刻！')

@require_GET
@login_required
def update_db_info(request):
    """
    更新资产信息信息
    :param request:
    :return:
    """
    update_rds_from_cloud.delay()
    return HttpResponse('任务已提交到后台，请稍等片刻！')


